package ferus.tigris.easymarks;

import java.util.ArrayList;
import java.util.List;

public class GameManager extends Thread {
	private GameView view;
	private boolean running = false;
	private SpriteFactory spriteFactory;
	private List<AbstractBehavior> personages = new ArrayList<AbstractBehavior>();
	private long lastTimeOfAddNewPersonage = 0;

	public void setRunning(boolean run) {
		running = run;
	}

	public GameManager(GameView gameView) {
		view = gameView;
		spriteFactory = new SpriteFactory(view);
	}
	
	public void run() {
		long ticksPS = 100;

		while (running) {
			long startTime = System.currentTimeMillis();
			synchronized (view.getHolder()) {
				update();
			}
			long sleepTime = ticksPS-(System.currentTimeMillis() - startTime);
			try {
				sleep(sleepTime < 10 ? 10 : sleepTime);
			} catch (InterruptedException e) {

			}
		}
	}

	private void update() {
		for(AbstractBehavior behavior: personages) {
			behavior.update();
		}
		if(personages.size() < 10) {
			if (System.currentTimeMillis() - lastTimeOfAddNewPersonage > 3000) {
				lastTimeOfAddNewPersonage = System.currentTimeMillis();
				synchronized (view.getHolder()) {
					AbstractBehavior personage = spriteFactory.createMiniCop();
					personages.add(personage);
					view.addView(personage.view());

					personage = spriteFactory.createAngel();
					personages.add(personage);
					view.addView(personage.view());
				}
			}
		}
	}
	
	public void onTouch(float x, float y) {
		long lastClick = 0;
		if (System.currentTimeMillis() - lastClick > 300) {
			lastClick = System.currentTimeMillis();
			for (int i = personages.size()-1; i >= 0; i--) 
			{
				AbstractBehavior personage = personages.get(i);
				if (personage.isCollition(x, y)) 
				{
					synchronized (view.getHolder()) {
						view.removeView(personage.view());
						personages.remove(personage);
					}
				}
			}
		}
	}

	public int scope() {
		return personages.size();
	}

}
